package com.sakura.mybatis.version4;

import org.apache.ibatis.executor.statement.StatementHandler;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.plugin.Intercepts;
import org.apache.ibatis.plugin.Invocation;
import org.apache.ibatis.plugin.Signature;

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.sql.Connection;
import java.util.Properties;

/**
 * @Author Sakura
 * @Date 2024/1/4 15:24
 * @Version 1.0
 */
@Intercepts({@Signature(type = StatementHandler.class, method = "prepare", args = {Connection.class, Integer.class})})
public class SqlInterceptor implements Interceptor {
    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        StatementHandler statementHandler = (StatementHandler) invocation.getTarget();
        String sql = statementHandler.getBoundSql().getSql();

        // 只记录非 SELECT 语句
        if (!sql.trim().toLowerCase().startsWith("select")) {
            Object parameterObject = statementHandler.getParameterHandler().getParameterObject();

            // 替换 SQL 语句中的问号占位符为参数值
            if (parameterObject != null) {
                String parameterValue = parameterObject.toString();
                sql = replaceParameters(sql, parameterValue);
            }

            try (BufferedWriter writer = new BufferedWriter(new FileWriter("sql_logs.txt", true))) {
                writer.write(sql);
                writer.newLine();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return invocation.proceed();
//        return null;
    }

    private String replaceParameters(String sql, String parameterValue) {
        // 在这里实现将问号替换为参数值的逻辑
        // 这取决于您的参数值和 SQL 语句的具体格式
        // 示例：将第一个问号替换为参数值
        return sql.replaceFirst("\\?", parameterValue);
    }

    @Override
    public void setProperties(Properties properties) {
    }
}